<template>
  <div class="poscontent">
    <div class="flex flexrowbetween bg_fff flexwrapper headerbox mb_14">
      <div></div>
      <div class="flex aligncenter mb_10">
        <div
          v-for="(item, index) in days"
          :key="index"
          class="dataname f-14 commhover"
          :class="{ active: daynum == item.value }"
          @click="handleClick(item)"
        >
          {{ item.name }}
        </div>
        <el-date-picker
          class="mr_20"
          v-model="time"
          size="small"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="changeTime"
        >
        </el-date-picker>
        <el-date-picker
          v-model="time1"
          class="mr_20"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="对比开始日期"
          end-placeholder="对比结束日期"
          @change="changeTime1">
        </el-date-picker>
        <!-- <el-button
          plain
          type="primary"
          class="exportbtn"
          size="small"
          @click="handleExport"
          >导出</el-button
        > -->
      </div>
    </div>
    <div class="bg_fff boxflex mb_20">
      <div class="flex f-16 c_000 aligncenter mb_20">
        <div class="line mr_10"></div>
        关键数据
      </div>
      <el-row :gutter="25" v-loading='loading1'>
        <el-col :span="25">
          <div class="bg_box">
            <div class="f-14 c_fff pb_10 box_h">消耗</div>
            <div class="flexrowbetween alignend">
              <div class="box_l">
                <div class="f-30 c_fff h_num">{{ datainfo.score|| 0 }}</div>
                <div class="f-14 c_fff mb_5">
                  同比
                  <i v-if="rate5 >= 0" class="el-icon-top c_34FF5B"></i>
                  <i v-else class="el-icon-bottom c_E50000"></i>
                  {{ rate5 }}%
                </div>
              </div>
              <div>
                <img src="@/assets/images/r1.png" alt="" class="box_rimg" />
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="25">
          <div class="bg_box bg1">
            <div class="f-14 c_fff pb_10 box_h">点击率</div>
            <div class="flexrowbetween alignend">
              <div class="box_l">
                <div class="f-30 c_fff h_num">{{ datainfo.click_ratio || 0}}%</div>
                <div class="f-14 c_fff mb_5">
                  同比
                  <i v-if="rate2 >= 0" class="el-icon-top c_34FF5B"></i>
                  <i v-else class="el-icon-bottom c_E50000"></i>
                  {{ rate2 }}%
                </div>
              </div>
              <div>
                <img src="@/assets/images/r2.png" alt="" class="box_rimg" />
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="25">
          <div class="bg_box bg2">
            <div class="f-14 c_fff pb_10 box_h">转化率</div>
            <div class="flexrowbetween alignend">
              <div class="box_l">
                <div class="f-30 c_fff h_num">{{ datainfo.transform_ratio || 0}}%</div>
                <div class="f-14 c_fff mb_5">
                  同比
                  <i v-if="rate2 >= 0" class="el-icon-top c_34FF5B"></i>
                  <i v-else class="el-icon-bottom c_E50000"></i>
                  {{ rate2 }}%
                </div>
              </div>
              <div>
                <img src="@/assets/images/r3.png" alt="" class="box_rimg" />
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="25">
          <div class="bg_box bg3">
            <div class="f-14 c_fff pb_10 box_h">平均转化成本</div>
            <div class="flexrowbetween alignend">
              <div class="box_l">
                <div class="f-30 c_fff h_num">
                  {{ datainfo.get_score || 0}}
                </div>
                <div class="f-14 c_fff mb_5">
                  同比
                  <i v-if="rate1 >= 0" class="el-icon-top c_34FF5B"></i>
                  <i v-else class="el-icon-bottom c_E50000"></i>
                  {{ rate1 }}%
                </div>
                <!-- <div class="f-14 c_fff mb_5">日均消耗  233</div> -->
              </div>
              <div>
                <img src="@/assets/images/r4.png" alt="" class="box_rimg" />
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="25">
          <div class="bg_box bg4">
            <div class="f-14 c_fff pb_10 box_h">转化数</div>
            <div class="flexrowbetween alignend">
              <div class="box_l">
                <div class="f-30 c_fff h_num">
                  {{ datainfo.broke || 0}}
                </div>
                <div class="f-14 c_fff mb_5">
                  同比
                  <i v-if="rate4 >= 0" class="el-icon-top c_34FF5B"></i>
                  <i v-else class="el-icon-bottom c_E50000"></i>
                  {{ rate4 }}%
                </div>
              </div>
              <div>
                <img src="@/assets/images/r5.png" alt="" class="box_rimg" />
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="bg_fff boxflex mb_20">
      <div class="flex f-16 c_000 aligncenter mb_20">
        <div class="line mr_10"></div>
        数据趋势
      </div>
      <div class="flex aligncenter mb_30" v-loading='loading2'>
        <div class="f-14 c_000 mr_30">数据指标</div>
        <el-checkbox-group v-model="resource">
          <el-checkbox
            v-for="(item, index) in typeList"
            :key="index"
            :label="item.id"
            class="mr_30"
            @change="changeType"
          >
            <span class="colorbox" :style="{ background: item.color }"></span>
            <template v-if="item.tip">
              <el-tooltip class="item" effect="light" :content="item.tip" placement="top-start">
                <span>{{ item.name }}</span>
              </el-tooltip>
            </template>
            <template v-else>
              <span>{{ item.name }}</span>
            </template>
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <div v-loading='loading2'>
        <line-chart
          :key="keys"
          :legendname="checkTypelist"
          :xAxis="xAxis"
          :chartData="lineChartData"
          height="420px"
        />
      </div>
    </div>
  </div>
</template>

<script>
import {
  allData,
  trendHourChart,
  trendDayChart,
  trendMonthChart,
} from "@/api/income";
import { time_date } from "@/utils/validate";
import LineChart from "@/components/Echart/LineChart";

export default {
  data() {
    return {
      queryParams: {
        page: 1,
        num: 10,
      },
      params: {
        position_id: "",
        plate_id: "",
      },
      positionlist: [],
      platelist: [],
      time: "",
      time1:'',
      loading1: false,
      loading2: false,
      days: [
        { name: "昨日", value: 1 },
        { name: "今日", value: 2 },
        { name: "本月", value: 3 },
        { name: "全年", value: 4 },
      ],
      daynum: 1,
      dataInfo: {
        click: { now: "", old: "" },
        get: { now: "", old: "" },
        transform_ratio: { now: "", old: "" },
        click_ratio: { now: "", old: "" },
        use: { now: "", old: "" },
      },
      rate1: "",
      rate2: "",
      rate3: "",
      rate4: "",
      rate5: "",
      datainfo: {
        broke: 0,
        click: 0,
        click_ratio: 0,
        get: 0,
        score: 0,
        transform_ratio: 0,
        ecpm: 0,
      },
      old_datainfo:{
        broke: 0,
        click: 0,
        click_ratio: 0,
        get: 0,
        score: 0,
        transform_ratio: 0,
        ecpm: 0,
      },
      tableData: [],
      total: 0,
      typeList: [
        { id: "get", name: "拉取量", value: 1, color: "#1670F1", tip:'当用户打开H5时，平台拉取广告于广告位，页面加载完成，说明当前用户广告拉取量为1.' },
        { id: "broke", name: "曝光量", value: 2, color: "#62B088" ,tip:'广告展示给用户的次数。计算方式: 经平台判定有效且被计费的展示次数'},
        {
          id: "transform_ratio",
          name: "曝光率（%）",
          value: 3,
          color: "#E50000",
          tip:'广告时间范围内广告实际到达的人数/可以覆盖人群总数=曝光率(曝光量/拉取量)'
        },
        { id: "click", name: "点击量", value: 4, color: "#F8C96B",tip:'当用户点击广告素材时，触发点击事件，该事件被认为是一次有效的广告点击' },
        { id: "click_ratio", name: "点击率（%）", value: 5, color: "#6D48E4",tip:'广告被点击的次数占展示次数的百分比。计算方法:点击数/展示数100%' },
        { id: "ecpm", name: "ecpm", value: 6, color: "#2D5D81",tip:'广告平均每一千次展现所付出的广告币，计算公式是: 总消耗/展示数*1000' },
        { id: "score", name: "收入", value: 7, color: "#1E2F4D" },
      ],
      resource: [],
      lineChartData: {},
      xAxis: [],
      keys: "",
    };
  },
  components: {
    LineChart,
  },
  created() {
    this.getDicts("/manager/api/planPositionList").then((res) => {
      this.positionlist = res.data;
    });
    this.getDicts("/manager/api/getPlateList").then((res) => {
      this.platelist = res.data;
    });
    this.typeList.forEach((item) => {
      this.resource.push(item.id);
    });
    this.getData();
    this.getList();
  },
  computed: {
    checkTypelist() {
      let arr = [];
      this.typeList.forEach((item) => {
        if (this.resource.includes(item.id)) {
          arr.push(item);
        }
      });
      // console.log('arr:', arr)
      return arr;
      // this.resource.map
    },
  },
  methods: {
    async getData() {
      let params = { };
      // if (this.params.position_id) {
      //   params.position_id = this.params.position_id;
      // }
      if (this.time) {
        params.start = this.time[0];
        params.end = this.time[1];
      }
      if (this.daynum == 1) {
        params.start = this.parseTime(time_date(-1).start, "{y}-{m}-{d}");
        params.end = this.parseTime(time_date(-1).start, "{y}-{m}-{d}");
      }
      if (this.daynum == 2) {
        params.start = this.parseTime(time_date(1).start, "{y}-{m}-{d}");
        params.end = this.parseTime(time_date(1).end, "{y}-{m}-{d}");
      }
      if (this.daynum == 3) {
        params.start = this.parseTime(time_date(30).start, "{y}-{m}-{d}");
        params.end = this.parseTime(time_date(30).end, "{y}-{m}-{d}");
      }
      if (this.daynum == 4) {
        params.start = this.parseTime(time_date(365).start, "{y}-{m}-{d}");
        params.end = this.parseTime(time_date(365).end, "{y}-{m}-{d}");
      }
      this.loading1 = true;

      allData(params).then((res) => {
        this.loading1 = false;
        this.datainfo = res.data;
        console.log('datainfo:', this.datainfo)
        this.getOldData()
      })
      .catch(() => {
        this.loading1 = false;
      });
    },

    getOldData(){
      let params = {};
      if (this.time) {
        params.start = this.time1[0];
        params.end = this.time1[1];
      }
      if (this.daynum == 1) {
        params.start = this.parseTime(time_date(-2).start, "{y}-{m}-{d}");
        params.end = this.parseTime(time_date(-2).start, "{y}-{m}-{d}");
      }
      if (this.daynum == 2) {
        params.start = this.parseTime(time_date(-1).start, "{y}-{m}-{d}");
        params.end = this.parseTime(time_date(-1).end, "{y}-{m}-{d}");
      }
      if (this.daynum == 3) {
        params.start = this.parseTime(time_date(-30).start, "{y}-{m}-{d}");
        params.end = this.parseTime(time_date(-30).end, "{y}-{m}-{d}");
      }
      if (this.daynum == 4) {
        params.start = this.parseTime(time_date(-365).start, "{y}-{m}-{d}");
        params.end = this.parseTime(time_date(-365).end, "{y}-{m}-{d}");
      }
      this.loading1 = true;
      allData(params).then((res) => {
        this.loading1 = false;
        this.old_datainfo = res.data;
        console.log('old_datainfo:', this.old_datainfo)
        this.setRata()
      })
      .catch(() => {
        this.loading1 = false;
      });
    },

    setRata(){
      let newdata = this.datainfo
      let olddata = this.old_datainfo
      // 点击率
      if (olddata.click_ratio == 0) {
        this.rate2 = 0;
      } else {
        this.rate2 = ((((newdata.click_ratio - olddata.click_ratio).toFixed(2)) / olddata.click_ratio)*100).toFixed(2);
      }

      // 消耗
      if (olddata.score == 0) {
        this.rate1 = 0;
      } else {
        this.rate1 = ((((newdata.score - olddata.score).toFixed(2)) / olddata.score)*100).toFixed(2);
      }

      // 转化率
      if (olddata.transform_ratio == 0) {
        this.rate3 = 0;
      } else {
        this.rate3 = ((((newdata.transform_ratio - olddata.transform_ratio).toFixed(2)) / olddata.transform_ratio)*100).toFixed(2);
      }

      // 平均转化成本
      if (olddata.get_score == 0) {
        this.rate4 = 0;
      } else {
        this.rate4 = ((((newdata.get_score - olddata.get_score).toFixed(2)) / olddata.get_score)*100).toFixed(2);
      }

      // 转化数
      if (olddata.broke == 0) {
        this.rate5 = 0;
      } else {
        this.rate5 = ((((newdata.broke - olddata.broke).toFixed(2)) / olddata.broke)*100).toFixed(2);
      }
    },

    handleClick(num) {
      this.daynum = num.value;
      this.time1 = ''
      this.time = ''
      this.handleQuery();
    },

    handleQuery() {
      this.queryParams.page = 1;
      this.getData();
      this.getList();
    },

    // changeTime(val) {
    //   if (val) {
    //     this.daynum = "";
    //   } else {
    //     this.daynum = 1;
    //   }
    //   this.handleQuery();
    // },
    changeTime() {
      if (this.time && this.time1) {
        this.daynum = "";
        this.handleQuery();
      }
    },

    changeTime1() {
      if (this.time && this.time1) {
        this.daynum = "";
        this.handleQuery();
      }
    },

    getList() {
      if (this.daynum == 1 || this.daynum == 2) {
        this.trendHourChart();
      }
      if (this.daynum == 3) {
        this.trendDayChart();
      }
      if (this.daynum == 4) {
        this.trendMonthChart();
      }
      if (this.time) {
        this.trendDayChart();
      }
    },

    trendHourChart() {
      let params = { ...this.queryParams };
      if (this.params.position_id) {
        params.position_id = this.params.position_id;
      }
      if (this.daynum == 1) {
        params.time = this.parseTime(time_date(-1).start, "{y}-{m}-{d}");
      }
      if (this.daynum == 2) {
        params.time = this.parseTime(time_date(1).start, "{y}-{m}-{d}");
      }
      this.loading2 = true;
      trendHourChart(params)
        .then((res) => {
          this.loading2 = false;
          this.tableData = res.data;
          this.changeLineData(res.data);
        })
        .catch(() => {
          this.loading2 = false;
        });
    },

    trendDayChart() {
      let params = { ...this.queryParams };
      if (this.params.position_id) {
        params.position_id = this.params.position_id;
      }
      if (this.daynum == 3) {
        params.start = this.parseTime(time_date(30).start, "{y}-{m}-{d}");
        params.end = this.parseTime(time_date(30).end, "{y}-{m}-{d}");
      }
      if (this.time) {
        params.start = this.time[0];
        params.end = this.time[1];
      }
      this.loading2 = true;
      trendDayChart(params)
        .then((res) => {
          this.loading2 = false;
          this.tableData = res.data;
          this.changeLineData(res.data);
        })
        .catch(() => {
          this.loading2 = false;
        });
    },

    trendMonthChart() {
      let params = { ...this.queryParams };
      if (this.params.position_id) {
        params.position_id = this.params.position_id;
      }
      if (this.daynum == 4) {
        params.start = this.parseTime(time_date(365).start, "{y}-{m}-{d}");
        params.end = this.parseTime(time_date(365).end, "{y}-{m}-{d}");
      }
      if (this.time) {
        params.start = this.time[0];
        params.end = this.time[1];
      }
      this.loading2 = true;
      trendMonthChart(params)
        .then((res) => {
          this.loading2 = false;
          this.tableData = res.data;
          this.changeLineData(res.data);
        })
        .catch(() => {
          this.loading2 = false;
        });
    },

    changeLineData(data) {
      // console.log(data);
      let params = {
        get: [],
        broke: [],
        transform_ratio: [],
        click: [],
        click_ratio: [],
        ecpm: [],
        score: [],
      };
      data.forEach((item) => {
        params.get.push(item.data.get);
        params.broke.push(item.data.broke);
        params.transform_ratio.push(item.data.transform_ratio);
        params.click.push(item.data.click);
        params.click_ratio.push(item.data.click_ratio);
        params.ecpm.push(item.data.ecpm);
        params.score.push(item.data.score);
      });
      // console.log('this.resource:', this.resource)
      let p_params = {};
      this.resource.map((item) => {
        p_params[item] = params[item];
      });
      this.lineChartData = p_params;
      this.xAxis = data.map((item) => item.time);
    },

    changeType() {
      console.log(this.resource);
      this.keys = Date.now();
      this.changeLineData(this.tableData);
    },

    handleExport() {},
  },
};
</script>

<style lang="scss" scoped>
.poscontent {
  // 56 导航栏的高 46 tab的高度 35 padding的高度
  height: calc(100vh - 60px);
  padding: 16px 16px 0 6px;
  //   overflow-y: auto;
  overflow-x: hidden;
}
.headerbox {
  padding: 10px 15px 0;
}
.dataname {
  margin-right: 22px;
  color: #8e8e8e;
  position: relative;
  &.active {
    color: #000;
  }
  &.active::after {
    position: absolute;
    content: "";
    width: 28px;
    height: 2px;
    background-color: #1670f1;
    bottom: -6px;
    left: 0;
  }
}
.boxflex {
  padding: 16px 20px;
  .line {
    width: 2px;
    height: 18px;
    background-color: #1670f1;
  }
}
.colorbox {
  display: inline-block;
  width: 20px;
  height: 10px;
}
.el-col-25 {
  width: 20%;
}
.bg_box {
  width: 100%;
  height: 160px;
  background: url("~@/assets/images/resf1.png") no-repeat;
  background-size: 100% 100%;
  padding: 15px 18px;
}
.bg1 {
  background: url("~@/assets/images/resf2.png") no-repeat;
  background-size: 100% 100%;
}
.bg2 {
  background: url("~@/assets/images/resf3.png") no-repeat;
  background-size: 100% 100%;
}
.bg3 {
  background: url("~@/assets/images/resf4.png") no-repeat;
  background-size: 100% 100%;
}
.bg4 {
  background: url("~@/assets/images/resf5.png") no-repeat;
  background-size: 100% 100%;
}
.box_h {
  border-bottom: 1px solid #fff;
}
.box_l {
  width: calc(100% - 60px);
}
.box_rimg {
  width: 60px;
  height: 60px;
}
.h_num {
  margin-top: 10px;
  margin-bottom: 10px;
}
.alignend{
  padding-top: 15px;
}
</style>
